package com.putong35.common.account.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.putong35.common.BuildConfig;
import com.putong35.common.account.Account;
import com.putong35.common.account.AccountManager;
import com.putong35.common.account.data.http.AccountApiHelper;
import com.putong35.common.baseactfrag.CompState;
import com.putong35.common.baseactfrag.activity.BaseActivity;
import com.putong35.common.databinding.ActivityLoginBinding;
import com.putong35.common.httprequest.UrlParams;
import com.putong35.common.httprequest.app.Token;
import com.putong35.common.httprequest.app.TokenInfo;
import com.putong35.common.utils.EasyToast;
import com.putong35.common.utils.RegularUtils;
import com.putong35.common.utils.ui.EditTextHelper;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {
    public static final String TAG = LoginActivity.class.getSimpleName();

    public static final int REQ_REGISTER = 1;
    public static final int REQ_FORGET_PASSWORD = 2;

    ActivityLoginBinding activityLoginBinding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideToolbar();
        statusTransucentAndLayoutFullscreen();
        EditTextHelper.setToPhoneType(activityLoginBinding.etAccountID);
        if (BuildConfig.DEBUG) {
            activityLoginBinding.etAccountID.setText("15375716870");
            activityLoginBinding.etPwd.setText("123456");
            activityLoginBinding.etAccountID.setText("15959234090");
            activityLoginBinding.etPwd.setText("111112");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AccountManager.getInstance().getAccount() != null) {
            setResult(RESULT_OK);
            EasyToast.showToast(this, "用户已登录");
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activityLoginBinding = ActivityLoginBinding.inflate(inflater);
        activityLoginBinding.setViewModel(this);
        activityLoginBinding.etAccountID.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override

            public void afterTextChanged(Editable editable) {
                String accountId = activityLoginBinding.etAccountID.getText().toString().trim();
                String pwd = activityLoginBinding.etPwd.getText().toString().trim();
                if (!TextUtils.isEmpty(accountId) && !TextUtils.isEmpty(pwd)) {
                    activityLoginBinding.btnLogin.setEnabled(true);
                } else {
                    activityLoginBinding.btnLogin.setEnabled(false);
                }
            }
        });
        activityLoginBinding.etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override

            public void afterTextChanged(Editable editable) {
                String accountId = activityLoginBinding.etAccountID.getText().toString().trim();
                String pwd = activityLoginBinding.etPwd.getText().toString().trim();
                if (!TextUtils.isEmpty(accountId) && !TextUtils.isEmpty(pwd)) {
                    activityLoginBinding.btnLogin.setEnabled(true);
                } else {
                    activityLoginBinding.btnLogin.setEnabled(false);
                }
            }
        });
        return activityLoginBinding.getRoot();
    }


    public void reqLogin() {

        String inputMobile = activityLoginBinding.etAccountID.getText().toString();
        String pwd = activityLoginBinding.etPwd.getText().toString().trim();

        if (TextUtils.isEmpty(inputMobile)) {
            EasyToast.showToast(this, "手机号码不能为空");
            return;
        }

        if (!RegularUtils.isMobileSimple(inputMobile)) {
            EasyToast.showToast(this, "请输入有效的手机号");
            return;
        }

        if (TextUtils.isEmpty(pwd)) {
            EasyToast.showToast(this, "密码不能为空");
            return;
        } else if (pwd.length() > 20 || pwd.length() < 6) {
            EasyToast.showToast(this, "请输入6-20位的密码");
            return;
        }


        setState(CompState.EMPTY_REFRESHING);
        AccountApiHelper.login(inputMobile, pwd, "", (code, msg, data, extObj) -> {
            Log.d(TAG, "onSuccess: " + data);
            TokenInfo tokenInfo = new TokenInfo();
            tokenInfo.setAccessToken(data.getToken());
            Token.getInstance().updateTokenInfo(tokenInfo);
            AccountManager.getInstance().setAccount(data);
            setState(CompState.DATA);
            EasyToast.showToast(LoginActivity.this, "登录成功");
            setResult(RESULT_OK);
            finish();

        }, (errCode, msg) -> {
            Log.d(TAG, "onFailure: " + msg);
            EasyToast.showToast(LoginActivity.this, msg);
            setState(CompState.DATA);
        });



        /*
        UrlParams urlParams = new UrlParams();
        urlParams.put("mobile", inputMobile);
        urlParams.put("password", pwd);

        setState(CompState.EMPTY_REFRESHING);
        Observable.create(e -> {
            TokenInfo tokenInfo = new TokenInfo();
            tokenInfo.setAccessToken("111111111111");
            tokenInfo.setExpiresAt("" + (System.currentTimeMillis() + 2000000000));
            tokenInfo.setMacKey("22222222");
            tokenInfo.setServerTime("" + System.currentTimeMillis());
            Token.getInstance().updateTokenInfo(tokenInfo);
            Thread.sleep(700);
            e.onComplete();
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("pww", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(Object value) {
                        Log.e("pww", "onNext: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("pww", "onError: ");
                        setState(CompState.DATA);
                    }

                    @Override
                    public void onComplete() {
                        Log.e("pww", "onComplete: ");
                        reqUserInfo("test token");
                    }
                });*/

    }


    public void reqUserInfo(String token) {
        UrlParams urlParams = new UrlParams();
        urlParams.put("token", token);

        setState(CompState.EMPTY_REFRESHING);
        Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
              /*  String responseStr = AssetsUtil.getStringFromAssets(context, "request_login_data.txt");
                Response parser = new Response(Account.class);
                parser.setDataString(responseStr);
                Account account = (Account) parser.getDataListBean();*/
                Account account = new Account();
               /* account.setName("小黄猫");
                account.setPhone("15959234090");
                account.setId("111111");
                String imgUrl = "http://img01.taopic.com/160203/235110-1602030ZP835.jpg";
                account.setPortraitUrl(imgUrl);
                account.setBirthday(new Date().getTime() - 1000*60*60*24*30);*/
                AccountManager.getInstance().setAccount(account);
                Thread.sleep(1500);
                e.onComplete();
            }
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.newThread())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("pww", "reqUserInfo onSubscribe: ");
                    }

                    @Override
                    public void onNext(Object value) {
                        Log.e("pww", "reqUserInfo onNext: ");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("pww", "reqUserInfo onError: ");
                        e.printStackTrace();
                        setState(CompState.DATA);
                    }

                    @Override
                    public void onComplete() {
                        setState(CompState.DATA);
                        EasyToast.showToast(LoginActivity.this, "登录成功");
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_REGISTER:
                if (resultCode == RESULT_OK) {
                    if (AccountManager.getInstance().getAccount() != null) {
                        setResult(RESULT_OK);
                        finish();
                    }
                }
                break;

        }
    }

}
